#!/bin/bash

# 清理构建文件和缓存，但保留dist目录
clean_build() {
    echo "Cleaning build files..."
    rm -rf build
    rm -rf *.egg-info
    find . -type d -name "__pycache__" -exec rm -rf {} +
    find . -type f -name "*.pyc" -delete
    find . -type f -name "*.pyo" -delete
    find . -type f -name "*.pyd" -delete
    find . -type d -name "*.dist-info" -exec rm -rf {} +
    find . -type d -name "*.egg-info" -exec rm -rf {} +
}

# 清理所有文件，包括dist目录
clean_all() {
    echo "Cleaning all build files..."
    clean_build
    rm -rf dist
}

# 创建新的虚拟环境
create_venv() {
    echo "Creating virtual environment..."
    rm -rf venv
    python3 -m venv venv
    source venv/bin/activate
    pip install --upgrade pip
    pip install --no-cache-dir -r requirements.txt
}

# 主构建过程
main() {
    # 清理所有之前的构建
    clean_all
    
    # 创建新的虚拟环境
    create_venv
    
    # 确保资源目录存在
    mkdir -p "contract_renamer/resources"
    
    # 检查并安装tesseract
    if ! command -v tesseract &> /dev/null; then
        echo "Installing Tesseract..."
        brew install tesseract
    fi
    
    # 检查中文语言包
    if [ ! -f "/usr/local/share/tessdata/chi_sim.traineddata" ]; then
        echo "Installing Tesseract Chinese language pack..."
        brew install tesseract-lang
    fi
    
    # 查找库文件
    find_library() {
        local name=$1
        local patterns=(
            "/usr/local/lib/lib${name}*.dylib"
            "/opt/homebrew/lib/lib${name}*.dylib"
            "/usr/local/opt/tesseract/lib/lib${name}*.dylib"
            "/opt/homebrew/opt/tesseract/lib/lib${name}*.dylib"
        )
        
        # 添加 brew 路径
        if [ "$name" = "tesseract" ]; then
            local brew_prefix=$(brew --prefix tesseract 2>/dev/null)
            if [ ! -z "$brew_prefix" ]; then
                patterns+=("${brew_prefix}/lib/lib${name}*.dylib")
            fi
        fi
        
        # 查找文件
        for pattern in "${patterns[@]}"; do
            local files=($(ls $pattern 2>/dev/null))
            for file in "${files[@]}"; do
                if [ -f "$file" ]; then
                    echo "$file"
                    return 0
                fi
            done
        done
        
        # 如果是 lept，尝试在 tesseract 依赖目录中查找
        if [ "$name" = "lept" ]; then
            local tesseract_prefix=$(brew --prefix tesseract 2>/dev/null)
            if [ ! -z "$tesseract_prefix" ]; then
                local deps_dir="${tesseract_prefix}/../"
                local lept_files=($(find "$deps_dir" -name "liblept*.dylib" -type f 2>/dev/null))
                if [ ${#lept_files[@]} -gt 0 ]; then
                    echo "${lept_files[0]}"
                    return 0
                fi
            fi
        fi
        
        return 1
    }
    
    # 获取 Tesseract 和 Leptonica 库路径
    echo "Finding library files..."
    TESSERACT_LIB=$(find_library "tesseract")
    LEPTONICA_LIB=$(find_library "lept")
    
    # 检查库文件是否存在
    if [ -z "$TESSERACT_LIB" ] || [ -z "$LEPTONICA_LIB" ]; then
        echo "Error: Required libraries not found"
        echo "Tesseract: $TESSERACT_LIB"
        echo "Leptonica: $LEPTONICA_LIB"
        
        # 显示更多调试信息
        echo -e "\nDebug information:"
        echo "Brew prefix: $(brew --prefix)"
        echo "Tesseract location: $(brew list tesseract)"
        echo "Library paths:"
        echo "/usr/local/lib:"
        ls -l /usr/local/lib/lib{tesseract,lept}* 2>/dev/null
        echo "/opt/homebrew/lib:"
        ls -l /opt/homebrew/lib/lib{tesseract,lept}* 2>/dev/null
        exit 1
    fi
    
    echo "Using libraries:"
    echo "Tesseract: $TESSERACT_LIB"
    echo "Leptonica: $LEPTONICA_LIB"
    
    # 构建应用
    echo "Building application..."
    python setup.py py2app --packages=contract_renamer
    
    # 检查构建结果
    if [ ! -d "dist/Contract Renamer.app" ]; then
        echo "Build failed: Application bundle not created"
        exit 1
    fi
    
    # 复制 Tesseract 可执行文件
    echo "Copying Tesseract files..."
    mkdir -p "dist/Contract Renamer.app/Contents/Resources/tesseract"
    cp -L $(which tesseract) "dist/Contract Renamer.app/Contents/Resources/tesseract/"
    
    # 复制 Tesseract 数据文件
    mkdir -p "dist/Contract Renamer.app/Contents/Resources/tessdata"
    cp -L /usr/local/share/tessdata/chi_sim.traineddata "dist/Contract Renamer.app/Contents/Resources/tessdata/"
    
    # 设置 Tesseract 路径
    echo "Setting up Tesseract paths..."
    mkdir -p "dist/Contract Renamer.app/Contents/Frameworks"
    
    # 复制实际的库文件（不是软链接）
    echo "Copying dynamic libraries..."
    cp -L "$TESSERACT_LIB" "dist/Contract Renamer.app/Contents/Frameworks/libtesseract.dylib"
    cp -L "$LEPTONICA_LIB" "dist/Contract Renamer.app/Contents/Frameworks/liblept.dylib"
    
    # 修复动态库依赖
    echo "Fixing library dependencies..."
    install_name_tool -change "$TESSERACT_LIB" "@executable_path/../Frameworks/libtesseract.dylib" "dist/Contract Renamer.app/Contents/Resources/tesseract/tesseract"
    install_name_tool -change "$LEPTONICA_LIB" "@executable_path/../Frameworks/liblept.dylib" "dist/Contract Renamer.app/Contents/Resources/tesseract/tesseract"
    install_name_tool -change "$LEPTONICA_LIB" "@executable_path/../Frameworks/liblept.dylib" "dist/Contract Renamer.app/Contents/Frameworks/libtesseract.dylib"
    
    # 验证库文件
    echo "Verifying libraries..."
    otool -L "dist/Contract Renamer.app/Contents/Frameworks/libtesseract.dylib"
    otool -L "dist/Contract Renamer.app/Contents/Frameworks/liblept.dylib"
    otool -L "dist/Contract Renamer.app/Contents/Resources/tesseract/tesseract"
    
    # 验证应用程序包
    echo "Verifying application bundle..."
    if [ -f "dist/Contract Renamer.app/Contents/MacOS/Contract Renamer" ]; then
        echo "Application bundle created successfully"
    else
        echo "Error: Application executable not found"
        exit 1
    fi
    
    # 创建 DMG 文件
    echo "Creating DMG file..."
    DMG_PATH="dist/Contract Renamer.dmg"
    TMP_DMG_PATH="dist/tmp.dmg"
    APP_PATH="dist/Contract Renamer.app"
    
    # 创建临时 DMG
    hdiutil create -size 200m -fs HFS+ -volname "Contract Renamer" "$TMP_DMG_PATH"
    
    # 挂载 DMG
    MOUNT_PATH=$(hdiutil attach "$TMP_DMG_PATH" | grep '/Volumes/' | cut -f 3)
    
    # 复制应用程序
    cp -R "$APP_PATH" "$MOUNT_PATH/"
    
    # 创建 Applications 链接
    ln -s /Applications "$MOUNT_PATH/Applications"
    
    # 设置图标和窗口属性（可选）
    if [ -f "contract_renamer/resources/icon.icns" ]; then
        cp "contract_renamer/resources/icon.icns" "$MOUNT_PATH/.VolumeIcon.icns"
        SetFile -a C "$MOUNT_PATH"
    fi
    
    # 卸载 DMG
    hdiutil detach "$MOUNT_PATH"
    
    # 转换为压缩格式
    hdiutil convert "$TMP_DMG_PATH" -format UDZO -o "$DMG_PATH"
    rm "$TMP_DMG_PATH"
    
    # 检查 DMG 文件
    if [ -f "$DMG_PATH" ]; then
        echo "DMG file created successfully"
    else
        echo "Error: DMG file creation failed"
        exit 1
    fi
}

# 捕获错误并清理所有
trap 'echo "Error occurred. Cleaning up..."; clean_all; deactivate 2>/dev/null; rm -rf venv; exit 1' ERR

# 运行主程序
main

# 成功完成后只清理构建文件，保留dist目录
echo "Build process completed successfully"
clean_build
deactivate
rm -rf venv

echo "Build artifacts are available in the dist directory" 